<script setup lang="ts">
import axios from 'axios'
import { nextTick, onMounted, ref } from 'vue'

const baseURL = 'http://localhost:8888'
axios.defaults.baseURL = baseURL

interface Message {
  timestamp: string
  content: {
    type: 'text' | 'image' | 'audio' | 'video'
    text?: string
    url?: string
  }
}

const messages = ref<Message[]>([])
const newMessage = ref('')
const fileInput = ref<HTMLInputElement | null>(null)
const messageListRef = ref<HTMLDivElement | null>(null)

const scrollToBottom = async () => {
  await nextTick()
  messageListRef.value?.scrollTo({
    top: messageListRef.value.scrollHeight,
    behavior: 'smooth'
  })
}


const fetchMessages = async () => {
  const { data } = await axios.get('/message/getAllMsg')
  console.log(data.data)

  messages.value = data.data
}

const sendTextMessage = async () => {
  if (!newMessage.value.trim()) return

  await axios.post('/message/sendText', {
    text: newMessage.value
  })
  newMessage.value = ''
  await fetchMessages()
}

const clearMsg = async () => {
  await axios.post('/message/clearMsg', {
    text: newMessage.value
  })
  await fetchMessages()
}

const handleFileUpload = async (e: Event) => {
  const target = e.target as HTMLInputElement
  if (!target.files?.length) return

  const formData = new FormData()
  formData.append('file', target.files[0])

  await axios.post('/message/sendFile', formData, {
    headers: { 'Content-Type': 'multipart/form-data' }
  })
  await fetchMessages()
}

const copyTextMessage = (text: string) => {
  navigator.clipboard.writeText(text).then(() => {
    alert('消息已复制到剪贴板')
  }).catch(err => {
    console.error('复制失败:', err)
  })
}

const downloadMedia = (url: string) => {
  fetch(url)
    .then(response => response.blob())
    .then(blob => {
      const link = document.createElement('a')
      const objectURL = URL.createObjectURL(blob)
      link.href = objectURL
      // @ts-ignore
      link.download = blob.name || 'image' // 使用提供的文件名，或blob的name属性，或默认名
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      URL.revokeObjectURL(objectURL) // 释放对象URL
    })
    .catch(error => {
      console.error('下载失败:', error)
    })
}
onMounted(() => {
  fetchMessages()
  setInterval(fetchMessages, 3000)

  setTimeout(async () => {
    await scrollToBottom()
  }, 200)
})
</script>

<template>
  <div class="chat-container">
    <div class="message-list" ref="messageListRef">
      <div v-for="(msg, index) in messages" :key="index" class="message-item">
        <div class="message-time">{{ new Date(msg.timestamp).toLocaleString() }}</div>

        <div class="message-content">
          <div v-if="msg.content.type === 'text'" class="text-message">
            {{ msg.content.text }}
            <button @click="copyTextMessage(msg.content.text ?? '')" class="copy-button">复制</button>
          </div>

          <div v-else-if="msg.content.type === 'image'" class="media-message">
            <img :src="baseURL + msg.content.url" style="width: 200px;height: 200px;" />
            <button @click="downloadMedia(baseURL + (msg.content.url ?? ''))" class="download-button">下载</button>
          </div>
          <video v-else-if="msg.content.type === 'video'" controls class="media-message">
            <source :src="baseURL + msg.content.url" />
          </video>
          <audio v-else-if="msg.content.type === 'audio'" controls class="media-message"
            :src="baseURL + msg.content.url" />

          <div v-else class="media-message-link">
            <a :href="baseURL + msg.content.url" target="_blank" rel="noopener noreferrer">{{
              msg.content.url?.split('/').pop() }}</a>
            <button @click="downloadMedia(baseURL + (msg.content.url ?? ''))" class="download-button">下载</button>
          </div>
        </div>

        <div class="message-buttons">
          <button class="copy-button" @click="clearMsg">清空</button>
        </div>
      </div>
    </div>

    <div class="input-area">
      <el-input type="textarea" autosize v-model="newMessage" @keyup.enter="sendTextMessage" placeholder="输入消息..."
        class="message-input" />
      <button @click="sendTextMessage" class="send-button">发送</button>
      <input type="file" ref="fileInput" @change="handleFileUpload" accept="image/*,audio/*,video/*" hidden />
      <button @click="fileInput?.click()" class="upload-button">
        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24">
          <path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z" />
        </svg>
      </button>
    </div>
  </div>
</template>

<style scoped>
.message-buttons {
  position: absolute;
  top: 10px;
  right: 10px;
  display: flex;
  gap: 5px;
}

.copy-button,
.download-button {
  padding: 5px 10px;
  border: none;
  border-radius: 4px;
  background: #007bff;
  color: white;
  cursor: pointer;
  transition: background 0.2s;
}

.copy-button:hover,
.download-button:hover {
  background: #0056b3;
}

.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f5f5f5;
}

.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background: #fff;
  box-shadow: inset 0 0 10px rgba(0, 0, 0, 0.05);
}

.message-item {
  margin-bottom: 15px;
  padding: 12px;
  border-radius: 8px;
  background: #f0f0f0;
  max-width: 70%;
}

.my-message {
  margin-left: auto;
  background: #e3f2fd;
}

.message-time {
  font-size: 12px;
  color: #666;
  margin-bottom: 4px;
}

.text-message {
  padding: 10px;
  word-break: break-word;
}

.media-message {
  max-width: 100%;
  max-height: 300px;
  border-radius: 4px;
}

.input-area {
  padding: 15px;
  display: flex;
  gap: 10px;
  background: #fff;
  border-top: 1px solid #eee;
}

.message-input {
  flex: 1;
  padding: 10px 15px;
  border-radius: 20px;
  outline: none;

}

.send-button,
.upload-button {
  padding: 10px 20px;
  border: none;
  border-radius: 20px;
  background: #1976d2;
  color: white;
  cursor: pointer;
  transition: background 0.2s;
}

.upload-button {
  padding: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.send-button:hover,
.upload-button:hover {
  background: #1565c0;
}
</style>
